import React from 'react';
import { Steps,Button,message,Form,Row,Col,Input,Select,Radio,Checkbox,Icon } from 'antd'
const Step = Steps.Step;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group
const steps = [{
  title: '创建档案基本信息',
  content: 'First',
}, {
  title: '设置资料清单',
  content: 'Second',
}, {
  title: '完成',
  content: 'Last',
}];
let uuid = 0;

class New extends React.Component{
	constructor(props){
		super(props)
		this.state={
			current:0,
			name:'',
			basicInfo:'',  //基础清单
			billInfo:'',   //资料清单
			type:0,  //0:电子档案模版 1:纸质档案模版
			names:'',  //基础清单的names
			types:'',  //基础清单的types
			in:'',  //基础清单的in
			infoName:'',  //资料清单的name
			infoType:'', //资料清单的type
			isFirstChange:false, //点击第一个下一步
			isSecondChange:false, //点击第二个下一步
		}
	}
	onChanges(){
		// console.log("123")
	}
	  next() {
	  	const { validateFields, getFieldsValue } = this.props.form
		validateFields((errors) => {
			if (errors) {
				return
			}
			const params = getFieldsValue()
			if(params.keys.length < 1){
				message.warning("至少选择一项基本信息")
				return
			}
			const {depTypes} = this.props
			var values=[];
			if(params.names.length > 0){
				
				for(let i=0;i<params.names.length;i++){
					if(params.names[i]){
						values.push({name:params.names[i],type:params.types[i],in:params.in[i]})
					}
					
				}
			}
			const current = this.state.current + 1;
			this.setState({ current, basicInfo:values, name:params.name,names:params.names,types:params.types,in:params.in,isFirstChange:true });
		})
	  }
	  next1(){
	  	const { validateFields, getFieldsValue } = this.props.form
		validateFields((errors) => {
			if (errors) {
				return
			}
			const params = getFieldsValue()
			if(params.keys1.length < 1){
				message.warning("至少选择一项基本信息")
				return
			}
			var listValue = []
			if(params.infoName.length > 0){
				for(let i=0;i<params.infoName.length;i++){
					var names1 = '';
					if(params.infoName[i]){
						params.infoType[i].map((item,j)=>{
							names1 += item + '#'
						})
						var names11 = names1.substring(0,names1.length-1)
						listValue.push({name:params.infoName[i],type:names11})
					}
				}
			}
			const current = this.state.current + 1;
			this.setState({ current, billInfo:listValue, infoName:params.infoName, infoType:params.infoType,isSecondChange:true });
		})
	  }
	  prev() {
	    const current = this.state.current - 1;
	    this.setState({ current });
	  }
	  component(){
	  	const params ={
	  		name:this.state.name,
	  		basicInfo:JSON.stringify(this.state.basicInfo),
	  		billInfo:JSON.stringify(this.state.billInfo),
	  		type:1,
	  	}

	  	const { onComponent,info,onUpdate } = this.props
	  	if(info){
	  		params.id = info.id
	  		onUpdate(params)
	  	}else{
	  		onComponent(params)
	  	}
	  	
	  }
  remove = (k) => {
    const { form } = this.props;
    const keys = form.getFieldValue('keys');
    if (keys.length === 1) {
      return;
    }

    form.setFieldsValue({
      keys: (keys).filter(key => key !== k),
    });
  }

  add = () => {
    uuid++;
    const { form } = this.props;
    const keys = form.getFieldValue('keys');
    const nextKeys = keys.concat({
    		name:"",
    		type:"",
    		in:"",
    });
    form.setFieldsValue({
      keys: nextKeys,
    });
  }	
  remove1 = (j) => {
    const { form } = this.props;
    const keys1 = form.getFieldValue('keys1');
    if (keys1.length === 1) {
      return;
    }

    form.setFieldsValue({
      keys1: (keys1).filter(key => key !== j),
    });
  }

  add1 = () => {
    const { form } = this.props;
    const keys1 = form.getFieldValue('keys1');
    const nextKeys = keys1.concat(uuid);
    uuid++;
    form.setFieldsValue({
      keys1: nextKeys,
    });
  }	    
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
      }
      
    });
  }  
  showMenu(i){
  	const { changeMenu } = this.props
  	changeMenu(i)
  }
	render(){
		const {info} = this.props
		const {isFirstChange,isSecondChange} = this.state
		var basicInfo = []
		var billInfo =[]
		if(info){
			basicInfo = info.basicInfo?JSON.parse(info.basicInfo):[]
			billInfo = info.billInfo?JSON.parse(info.billInfo):[] 
		}
		
		const { getFieldDecorator, getFieldValue } = this.props.form;
		const formItemLayout1 = {
			labelCol: { span: 3 },
			wrapperCol: { span: 21 },
		};
		const formItemLayout2 = {
			labelCol: { span: 6 },
			wrapperCol: { span: 18 },
		};
		const formItemLayout3 = {
			labelCol: { span: 8 },
			wrapperCol: { span: 16 },
		}
	//基本信息
    getFieldDecorator('keys', { initialValue: basicInfo && isFirstChange == false?basicInfo:this.state.basicInfo });
    const keys = getFieldValue('keys');
    const formItems = keys.map((k, index) => {
      return (
      	<Row key={index} gutter={24} style={{ marginBottom: 8,marginTop:16 }}>
      		<Col lg={8} md={6} sm={6} xs={8}>
		        <FormItem
		          {...formItemLayout2}
		          label="字段名称:"
		          required={false}
		        >
		          {getFieldDecorator(`names[${index}]`, {
		          	initialValue:basicInfo[index] && isFirstChange == false ? k.name : this.state.names[index],
//					initialValue:k.name,
//		            validateTrigger: ['onChange', 'onBlur'],	
		            rules: [{
		              required: true,
		              message: "请填写字段名称",
		            }],
		          })(
		            		<Input placeholder="请填写字段名称" />
		          )}
		
		        </FormItem>   
		    </Col>    
		    <Col lg={8} md={6} sm={6} xs={8}>
		        <FormItem
		          {...formItemLayout2}
		          label="字段类型"
		          required={false}
		        >
		          {getFieldDecorator(`types[${index}]`, {
		          	initialValue:basicInfo[index] && isFirstChange == false ? k.type : this.state.types[index],
//					initialValue:k.type,
//		            validateTrigger: ['onChange', 'onBlur'],
		            rules: [{
		              required: true,
		              message: "请填写字段类型",
		            }],
		          })(
		          	<Select
						style={{ width: '100%' }}
						placeholder="请选择字段类型"
					>
						<Option key="字符串型">字符串型</Option>
						<Option key="日期型">日期型</Option>
					</Select>
		          )}       
		         </FormItem> 
	        </Col> 
	        <Col lg={6} md={2} sm={2} xs={4}>
	        <FormItem
	          {...formItemLayout3}
	          label="是否必填"
	          required={false}
	        >
	          {getFieldDecorator(`in[${index}]`, {
	          	initialValue: basicInfo[index] && isFirstChange == false ? k.in : this.state.in[index],
//				initialValue:k.in,
//	            validateTrigger: ['onChange', 'onBlur'],
	            rules: [{
	              required: true,
	              message: "请选择是否必填",
	            }],
	          })(
	          	<RadioGroup>
			        <Radio value="是">是</Radio>
			        <Radio value="否">否</Radio>
			    </RadioGroup>
	          )}       
	         </FormItem> 
	        </Col> 
	        {keys.length > 1 ? (
	        	<Col lg={2} md={2} sm={2} xs={2}>
	            <Button
	              className="dynamic-delete-button"
	              disabled={keys.length === 1}
	              onClick={() => this.remove(k)}
	            >删除
	            </Button>
	       </Col>     
	          ) : null}
        </Row>
      );
    });		
    //资料清单
    const plainOptions = [
	  { label: '本地', value: '本地' },
	  { label: '扫描', value: '扫描' },
	  { label: '拍照', value: '拍照' },
	  { label: '录像', value: '录像' }
	];
    getFieldDecorator('keys1', { initialValue: billInfo?billInfo:[] });
    const keys1 = getFieldValue('keys1');
    const formItems1 = keys1.map((j, index) => {
      return (
      	<Row key={index} gutter={24} style={{ marginBottom: 8,marginTop:16 }}>
      		<Col lg={10} md={6} sm={6} xs={10}>
		        <FormItem
		          {...formItemLayout2}
		          label="资料名称:"
		          required={false}
		        >
		          {getFieldDecorator(`infoName[${index}]`, {
//		          	initialValue:billInfo[index] && isSecondChange == false ? j.name : this.state.infoName[index],
					initialValue:j.name,
//		            validateTrigger: ['onChange', 'onBlur'],
		            rules: [{
		              required: true,
		              message: "请填写字段名称",
		            }],
		          })(
		            		<Input placeholder="请填写字段名称" />
		          )}
		
		        </FormItem>   
		    </Col>    
	        <Col lg={10} md={6} sm={6} xs={10}>
	        <FormItem
	          {...formItemLayout3}
	          label="采集方式"
	          required={false}
	        >
	          {getFieldDecorator(`infoType[${index}]`, {
//	          	initialValue:billInfo[index] && isSecondChange == false ? j.type.split("#") : this.state.infoType[index],
	          	initialValue:j.type?j.type.split("#"):'',
//		        initialValue:['拍照','录像'],	            
//	            validateTrigger: ['onChange', 'onBlur'],
	            rules: [{
	              required: true,
	              message: "请选择至少一项采集方式",
	            }],
	          })(
	          	    <CheckboxGroup options={plainOptions} />
	          )}       
	         </FormItem> 
	        </Col> 
	        {keys1.length > 1 ? (
	        	<Col lg={4} md={2} sm={2} xs={4}>
	            <Button
	              className="dynamic-delete-button"
	              disabled={keys1.length === 1}
	              onClick={() => this.remove1(j)}
	            >删除
	            </Button>
	       </Col>     
	          ) : null}
        </Row>
      );
    });   
		return(
			<Form>
				<Button type="primary" style={{marginBottom:10}} onClick={this.showMenu.bind(this,2)}>
		        		<Icon type="left" />返回
		    		</Button>
				<Steps current={this.state.current}>
					{steps.map(item => <Step key={item.title} title={item.title} />)}
				</Steps>
				{
					steps[this.state.current].content == 'First'?
					
					<div style={{ width: "80%", marginLeft: "10%", marginTop: 20 }}>
						<div>
							<span style={{fontSize:16,fontWeight:600}}>请输入文档名称</span>
						</div>
						<Row gutter={24} style={{ marginBottom: 8,marginTop:16 }}>
							<FormItem
								label="文档名称："
								{...formItemLayout1}>
								{getFieldDecorator('name', {
									initialValue: info.name && isFirstChange==false ? info.name : this.state.name,
									rules: [{ required: true, message: '文档名称不能为空' }],
								})(
									<Input placeholder="请填写文档名称"/>
								)}
							</FormItem>
						</Row>	
						<div>
							<span style={{fontSize:16,fontWeight:600}}>请根据您的需求添加文档基本信息</span>
							<Button type='primary' onClick={this.add} style={{marginLeft:10}}>添加字段</Button> 
						</div>
						<Row>
							 {formItems}
						</Row>
					</div>
					
					:steps[this.state.current].content == 'Second'?
					
					<div style={{ width: "80%", marginLeft: "10%", marginTop: 20 }}>
						<div>
							<span style={{fontSize:16,fontWeight:600}}>请根据您的需求添加文档基本信息</span>
							<Button type='primary' onClick={this.add1} style={{marginLeft:10}}>添加字段</Button> 
						</div>
						<Row>
							 {formItems1}
						</Row>
					</div>:
					
					<div style={{ width: "60%", marginLeft: "20%" }}>
							<div style={{ textAlign: 'center' }}>
								<img src={require('../../../assets/complete.png')} style={{ width: 80, margin: 5 }} />
								<h5 style={{ fontSize: 24, textAlign: "center", fontWeight: 600 }}>操作成功</h5>
							</div>
							<div style={{ textAlign: 'center',margin:"20px 0",fontSize:16 }}>
								<p>您的电子档案模板 <span style={{color:"#0099FF"}}>{this.state.name}</span> 已创建成功，您可在电子资料模板管理中对其进行编辑！ </p>
							</div>
					</div>
				}
				<div style={{textAlign:'center'}}>
					{
						this.state.current > 0
						&&
						<Button style={{marginLeft:8}} onClick={()=>this.prev()}>
						上一步
						</Button>
					}
					{
						this.state.current === 0 && this.state.current < steps.length - 1
						&&
						<Button type='primary' style={{marginLeft:8}} onClick={()=> this.next()}>下一步</Button>
					}
					{
						this.state.current > 0 && this.state.current < steps.length - 1
						&&
						<Button type="primary" style={{ marginLeft: 10 }} onClick={() => this.next1()}>下一步</Button>			
					}
					{
						this.state.current === steps.length -1
						&&
						<Button type='primary' style={{marginLeft:8}} onClick={()=> this.component()}>完成</Button>
					}
				</div>	
			</Form>
		)
	}
}

export default Form.create()(New)

